/*
 * Lightweight event bus
 *
 * history:
 *  2021-06-13 yao yu created
 */

#include "EventBusLite.h"

// global event bus define

static EventBusLite s_event_bus;

/*
 * event bus implement
 */

inline bool EventBusLite::attach(int msgid, EventCB callback)
{
    auto it = m_events_map.find(msgid);
    if (it == m_events_map.end())
    {
        m_events_map[msgid] = std::list<EventCB>();
    }
    m_events_map[msgid].push_back(callback);
    return true;
}

inline bool EventBusLite::detach(int msgid, EventCB callback)
{
    auto it = m_events_map.find(msgid);
    if (it != m_events_map.end())
    {
        it->second.remove(callback);
        return true;
    }
    return false;
}

inline bool EventBusLite::attach(int msgid, Observer *functor)
{
    auto it = m_functor_map.find(msgid);
    if (it == m_functor_map.end())
    {
        m_functor_map[msgid] = std::list<Observer *>();
    }
    m_functor_map[msgid].push_back(functor);
    return true;
}

inline bool EventBusLite::detach(int msgid, Observer *functor)
{
    auto it = m_functor_map.find(msgid);
    if (it != m_functor_map.end())
    {
        it->second.remove(functor);
        return true;
    }
    return false;
}

inline void EventBusLite::notify(int msgid, void **pUser)
{
    auto it = m_events_map.find(msgid);
    if (it != m_events_map.end())
    {
        for (auto cb : it->second)
        {
            cb(msgid, pUser);
        }
    }
    auto it2 = m_functor_map.find(msgid);
    if (it2 != m_functor_map.end())
    {
        for (auto cb : it2->second)
        {
            (*cb)(msgid, pUser);
        }
    }
}

/*
 * global event bus implement
 */

bool ge_attach(int msgid, EventCB callback)
{
    return s_event_bus.attach(msgid, callback);
}

bool ge_detach(int msgid, EventCB callback)
{
    return s_event_bus.detach(msgid, callback);
}

bool ge_attach(int msgid, Observer *functor)
{
    return s_event_bus.attach(msgid, functor);
}

bool ge_detach(int msgid, Observer *functor)
{
    return s_event_bus.detach(msgid, functor);
}

void ge_notify(int msgid, void **pUser)
{
    return s_event_bus.notify(msgid, pUser);
}